package adv7.udp;

import java.io.*;
import java.net.*;

public class EchoServer {
	private int port = 8000;
	private DatagramSocket socket;

	public EchoServer() throws IOException {
		socket = new DatagramSocket(port);
		System.out.println("服务端小广播启动成功");
	}

	public String echo(String msg) {
		return "朕知道了:" + msg;
	}

	public void service() {
		while (true) {
			try {
				DatagramPacket packet = new DatagramPacket(new byte[512], 512);
				socket.receive(packet);
				String msg = new String(packet.getData(), 0, packet.getLength());
				System.out.println(packet.getAddress() + ":" + packet.getPort() + ">" + msg);

				packet.setData(echo(msg).getBytes());
				socket.send(packet);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String args[]) throws IOException {
		new EchoServer().service();
	}
}
